package edu.chinasoft.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.annotation.WebServlet;
import org.apache.log4j.Logger;

import edu.chinasoft.pojo.Goods;
import edu.chinasoft.service.GoodsService;
import edu.chinasoft.service.GoodsServiceImp;

/**
 * 
 * @author cjogng
 * @date 2020年1月16日:下午5:31:16
 * @version V1.0
 * @Description:
 */
@WebServlet(name = "myFindGoodsByIdForServlet", value = "/servlet/findgoodsbyidforservlet")
public class FindGoodsByIdForServlet extends HttpServlet {
	private static Logger logger = Logger.getLogger(FindGoodsByIdForServlet.class);
	private GoodsService goodsService = new GoodsServiceImp();

	/**
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.debug(" FindGoodsByIdForServlet >doGet start.......");
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();

		// 获取所要查询商品的id
		String idString = request.getParameter("id");
		int id = Integer.parseInt(idString);

		// 把id值封装到pojo里，然后调用服务器层返回商品的其他信息
		Goods goods = new Goods();
		goods.setId(id);
		Goods result = goodsService.findGoodsInfo(goods);

		// 把商品的id_名称添加到Cookie

		String cookValue=this.getCookieValue(request,result,3);
		
		logger.debug(cookValue);
		
		Cookie cookie = new Cookie("lookgoods", cookValue);
		cookie.setMaxAge(1 * 60 * 30);
		cookie.setPath(request.getContextPath());
		response.addCookie(cookie);

		// 把信息封装到html,然后显示
		out.write(
				"<html lang='en'>    <head>    	<meta charset='UTF-8'>    	<title>显示商品详细信息</title>    </head>    <body>     <h2 align='center'>商品详细信息</h2>     <table width='60%' align='center' border='1px' cellpadding='0' cellpadding='0'>            <tr align='center'>       <td>商品名称</td>       <td>商品描述</td>       <td>商品价格</td>       <td>商品库存</td>      </tr>");

		out.write(" <tr align='center'>       <td>" + result.getGoodsName() + "</td>       <td>" + result.getGoodsDesc()
				+ "</td>       <td>" + result.getGoodsPrice() + "</td>       <td>" + result.getGoodsStock()
				+ "</td>      </tr>");

		out.write("</table> </body> </html>");

		logger.debug(" FindGoodsByIdForServlet >doGet end.......");
	}

	private String getCookieValue(HttpServletRequest request, Goods goods, int zuJiMax) {
		// TODO Auto-generated method stub
		String cookeValue = "";
		String cookeContentLook = goods.getId()+":"+goods.getGoodsName();
		Cookie[] cookieArray = request.getCookies();
		if (cookieArray != null) {
			for (Cookie element : cookieArray) {
				if (element.getName().equals("lookgoods")) {
					cookeValue = element.getValue();
				}
			}
		}

		if (cookeValue.equals("")) { // 第一次查看商品信息
			cookeValue = cookeContentLook;
		} else { // 非第一次查看商品信息

			String[] zuJiArray = cookeValue.split("#");
			List<String> zuJiList = Arrays.asList(zuJiArray);
			LinkedList zuJiLinkedList = new LinkedList<String>(zuJiList);

			if (zuJiLinkedList.size() == zuJiMax) { // 当足迹是3
				if (zuJiLinkedList.contains(cookeContentLook)) { // 如果足迹里已经包含当前访问的商品
					zuJiLinkedList.remove(cookeContentLook); // 先删除该商品
					zuJiLinkedList.addFirst(cookeContentLook); // 把该商品放在第一位
				} else { // 如果足迹里没有包含当前访问的商品
					zuJiLinkedList.removeLast(); // 把最后一个商品删除
					zuJiLinkedList.addFirst(cookeContentLook); // 把该商品放在第一位
				}
			} else { // 当足迹小于3
				if (zuJiLinkedList.contains(cookeContentLook)) { // 如果足迹里已经包含当前访问的商品
					zuJiLinkedList.remove(cookeContentLook); // 先删除该商品
					zuJiLinkedList.addFirst(cookeContentLook); // 把该商品放在第一位
				} else { // 如果足迹里没有包含当前访问的商品
					zuJiLinkedList.addFirst(cookeContentLook); // 把该商品放在第一位
				}

			}
			
			cookeValue=listToString(zuJiLinkedList);
			
			

		}

		return cookeValue;

	}
	
	public String   listToString(List<String> list) {
		String result="";
		
		for(String element:list) {
			result+=element+"#";	
		}
		
		result = result.substring(0, result.length()-1);
		
		return result;
	}
	

	/**
	 * 
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.debug(" FindGoodsByIdForServlet >doPost start.......");
		this.doGet(request, response);

		logger.debug(" FindGoodsByIdForServlet >doPost end.......");
	}

}